<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { openPaymentModal, checkAccessPermission, formatPrice } from '../utils/paymentUtils.js'

const router = useRouter()

// 模拟用户登录状态和会员等级
const userInfo = ref({
  username: '',
  level: '游客', // 游客、学子会员、传人会员、大师会员
  isLoggedIn: false
})

// 获取Vue应用实例，用于调用全局方法
const app = getCurrentInstance()

// 现代改编剧目数据
const modernAdaptations = [
  {
    id: 1,
    title: '新白蛇传',
    cover: 'https://picsum.photos/id/140/400/500',
    description: '融合现代元素的创新改编，讲述白素贞与许仙跨越千年的爱情故事。',
    duration: '105分钟',
    year: '2023',
    tags: ['爱情', '创新', '现代改编'],
    isExclusive: true,
    price: 39,
    discountPrice: 29.9,
    rating: 4.8,
    reviewCount: 356,
    previewVideo: '#',
    fullVideo: '#',
    highlights: [
      '数字首演，4K超清画质',
      '融合现代音乐元素',
      '全新角色设计',
      '导演特别解说版'
    ]
  },
  {
    id: 2,
    title: '现代西游记',
    cover: 'https://picsum.photos/id/141/400/500',
    description: '将经典《西游记》搬到现代都市背景，重新演绎师徒四人的奇幻冒险。',
    duration: '150分钟',
    year: '2023',
    tags: ['奇幻', '喜剧', '系列'],
    isExclusive: true,
    isSeries: true,
    episodes: 8,
    price: 129,
    discountPrice: 99,
    rating: 4.9,
    reviewCount: 523,
    previewVideo: '#',
    fullVideo: '#',
    highlights: [
      '8集完整系列',
      '每集独立故事',
      '现代都市奇幻设定',
      '独家花絮拍摄'
    ]
  },
  {
    id: 3,
    title: '创作者访谈合集',
    cover: 'https://picsum.photos/id/142/400/500',
    description: '深度对话皮影艺术家，揭秘创作背后的故事和艺术理念。',
    duration: '180分钟',
    year: '2022',
    tags: ['纪录片', '访谈', '艺术'],
    isExclusive: true,
    price: 79,
    discountPrice: 59.9,
    rating: 4.7,
    reviewCount: 218,
    previewVideo: '#',
    fullVideo: '#',
    highlights: [
      '12位艺术家专访',
      '创作过程全记录',
      '艺术理念分享',
      '收藏级画质'
    ]
  },
  {
    id: 4,
    title: '制作过程全记录',
    cover: 'https://picsum.photos/id/143/400/500',
    description: '从构思到舞台，完整记录一部皮影剧目的诞生全过程。',
    duration: '240分钟',
    year: '2022',
    tags: ['纪录片', '制作', '幕后'],
    isExclusive: true,
    price: 99,
    discountPrice: 79.9,
    rating: 4.6,
    reviewCount: 187,
    previewVideo: '#',
    fullVideo: '#',
    highlights: [
      '创作手稿展示',
      '角色设计过程',
      '舞台搭建细节',
      '排练花絮集锦'
    ]
  }
]

// 数字藏品数据
const digitalCollectibles = [
  {
    id: 1,
    name: '联名皮影NFT',
    image: 'https://picsum.photos/id/144/300/300',
    description: '限量发行的数字艺术收藏品，具有唯一性认证。',
    price: 199,
    limitedQuantity: 100,
    remainingQuantity: 43,
    rating: 5.0,
    reviewCount: 57
  },
  {
    id: 2,
    name: '数字艺术海报',
    image: 'https://picsum.photos/id/145/300/300',
    description: '高清数字艺术海报，可下载收藏，支持个性化签名。',
    price: 59,
    limitedQuantity: 300,
    remainingQuantity: 124,
    rating: 4.5,
    reviewCount: 176
  },
  {
    id: 3,
    name: '虚拟角色皮肤',
    image: 'https://picsum.photos/id/146/300/300',
    description: '可在互动体验中使用的角色皮肤，独家设计。',
    price: 89,
    limitedQuantity: 200,
    remainingQuantity: 78,
    rating: 4.7,
    reviewCount: 122
  }
]

// 加载用户信息
onMounted(() => {
  const loginStatus = localStorage.getItem('isLoggedIn') === 'true'
  userInfo.value.isLoggedIn = loginStatus
  
  if (loginStatus) {
    const storedUserInfo = localStorage.getItem('userInfo')
    if (storedUserInfo) {
      const parsed = JSON.parse(storedUserInfo)
      userInfo.value.username = parsed.username || parsed.phone || ''
      userInfo.value.level = parsed.level || '普通会员'
    }
  }
})

// 计算用户权限
const userPermissions = computed(() => {
  switch (userInfo.value.level) {
    case '学子会员':
      return {
        canWatchAdaptations: false,
        canWatchMasterContent: false,
        discountRate: 0.9
      }
    case '传人会员':
      return {
        canWatchAdaptations: true,
        canWatchMasterContent: false,
        discountRate: 0.85
      }
    case '大师会员':
      return {
        canWatchAdaptations: true,
        canWatchMasterContent: true,
        discountRate: 0.8
      }
    default:
      return {
        canWatchAdaptations: false,
        canWatchMasterContent: false,
        discountRate: 1
      }
  }
})

// 处理内容购买
const handlePurchase = (item) => {
  if (!userInfo.value.isLoggedIn) {
    router.push('/login')
    return
  }
  
  // 检查用户是否已经有权限（部分会员可能已包含此内容）
  const canAccess = item.memberIncluded && checkAccessPermission(item.accessLevel)
  
  if (canAccess) {
    alert(`您的会员等级已包含《${item.title || item.name}》的访问权限！`)
    return
  }
  
  // 计算最终价格
  const finalPrice = item.discountPrice || item.price
  
  // 显示购买确认
  if (confirm(`确认购买「${item.title || item.name}」，价格：${formatPrice(finalPrice)}？`)) {
    // 打开支付模态框
    openPaymentModal(app?.proxy, {
      id: item.id,
      name: item.title || item.name,
      price: finalPrice,
      type: item.type || 'exclusive_content',
      details: item.description
    })
  }
}

// 处理观看按钮点击
const handleWatch = (item) => {
  if (!userInfo.value.isLoggedIn) {
    router.push('/login')
    return
  }
  
  // 检查用户是否有权限观看
  const hasAccess = checkAccessPermission(item.accessLevel)
  
  if (hasAccess || userPermissions.value.canWatchAdaptations) {
    // 会员可直接观看
    alert(`即将播放《${item.title}》`)
  } else {
    // 非会员需要购买
    handlePurchase(item)
  }
}

// 处理会员升级
const upgradeMembership = () => {
  router.push('/membership')
}
</script>

<template>
  <div class="modern-adaptations-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">现代改编</h1>
      <p class="page-subtitle">传统艺术，现代演绎</p>
    </div>

    <!-- 会员提示横幅 -->
    <div class="membership-banner">
      <div class="container">
        <div class="banner-content">
          <div class="banner-text">
            <h3>✨ 独家原创内容</h3>
            <p v-if="userInfo.isLoggedIn">
              您当前是 <span class="user-level">{{ userInfo.level }}</span>，
              <template v-if="userPermissions.canWatchAdaptations">
                可免费观看所有现代改编剧目！
              </template>
              <template v-else>
                可享受专属折扣，升级会员免费观看全部内容。
              </template>
            </p>
            <p v-else>
              登录后可观看免费预览，独家内容限时优惠！
            </p>
          </div>
          <div class="banner-actions">
            <button v-if="!userInfo.isLoggedIn" class="btn btn-primary" @click="router.push('/login')">
              立即登录
            </button>
            <button v-else-if="!userPermissions.canWatchAdaptations" 
                    class="btn btn-primary" @click="upgradeMembership">
              升级会员
            </button>
            <button v-else class="btn btn-outline">
              会员中心
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 独家原创剧目 -->
    <div class="section container">
      <div class="section-header">
        <h2 class="section-title">🎬 独家原创剧目</h2>
        <p class="section-subtitle">融合传统与现代的创新之作</p>
      </div>
      
      <div class="content-grid">
        <div v-for="item in modernAdaptations" :key="item.id" class="content-card">
          <!-- 内容封面 -->
          <div class="content-cover">
            <img :src="item.cover" :alt="item.title" class="cover-image" />
            <!-- 独家标识 -->
            <div class="exclusive-badge">
              <span class="badge-text">独家</span>
            </div>
            <!-- 评分 -->
            <div class="rating-badge">
              <span class="rating-stars">⭐</span>
              <span class="rating-score">{{ item.rating }}</span>
              <span class="rating-count">({{ item.reviewCount }})</span>
            </div>
          </div>
          
          <!-- 内容信息 -->
          <div class="content-info">
            <h3 class="content-title">{{ item.title }}</h3>
            
            <!-- 系列信息 -->
            <div v-if="item.isSeries" class="series-info">
              <span class="series-tag">系列</span>
              <span class="episode-count">{{ item.episodes }}集全</span>
            </div>
            
            <p class="content-description">{{ item.description }}</p>
            
            <!-- 亮点 -->
            <div class="highlights">
              <div v-for="(highlight, index) in item.highlights.slice(0, 2)" :key="index" class="highlight-item">
                <span class="highlight-icon">✨</span>
                <span class="highlight-text">{{ highlight }}</span>
              </div>
            </div>
            
            <!-- 价格和操作 -->
            <div class="content-actions">
              <div class="price-info">
                <span class="discount-price">¥{{ item.discountPrice || item.price }}</span>
                <span v-if="item.discountPrice" class="original-price">¥{{ item.price }}</span>
              </div>
              
              <button 
                v-if="userPermissions.canWatchAdaptations"
                class="btn btn-primary"
                @click="handleWatch(item)"
              >
                立即观看
              </button>
              <button 
                v-else
                class="btn btn-primary"
                @click="handlePurchase(item)"
              >
                立即购买
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 数字藏品 -->
    <div class="section container">
      <div class="section-header">
        <h2 class="section-title">🎨 数字藏品专区</h2>
        <p class="section-subtitle">限量版数字艺术收藏品</p>
      </div>
      
      <div class="collectibles-grid">
        <div v-for="item in digitalCollectibles" :key="item.id" class="collectible-card">
          <div class="collectible-image">
            <img :src="item.image" :alt="item.name" class="item-image" />
            <!-- 限量标识 -->
            <div class="limited-badge">
              <span class="badge-text">限量</span>
            </div>
          </div>
          
          <div class="collectible-info">
            <h3 class="collectible-name">{{ item.name }}</h3>
            <p class="collectible-description">{{ item.description }}</p>
            
            <!-- 数量信息 -->
            <div class="quantity-info">
              <span class="quantity-label">库存：</span>
              <span class="quantity-remaining">{{ item.remainingQuantity }}/{{ item.limitedQuantity }}</span>
            </div>
            
            <!-- 评分和价格 -->
            <div class="collectible-footer">
              <div class="collectible-rating">
                <span class="rating-stars">⭐</span>
                <span class="rating-score">{{ item.rating }}</span>
                <span class="rating-count">({{ item.reviewCount }})</span>
              </div>
              <div class="collectible-price">
                ¥{{ item.price }}
              </div>
            </div>
            
            <!-- 购买按钮 -->
            <button 
              class="btn btn-primary full-width"
              @click="handlePurchase(item)"
              :disabled="item.remainingQuantity <= 0"
            >
              {{ item.remainingQuantity > 0 ? '立即购买' : '已售罄' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 促销活动 -->
    <div class="promotion-section container">
      <div class="promotion-card">
        <div class="promotion-header">
          <h3 class="promotion-title">🎉 新用户限时特惠</h3>
          <p class="promotion-subtitle">首月特惠：学子会员 ¥9.9</p>
        </div>
        <div class="promotion-content">
          <div class="promotion-offers">
            <div class="offer-item">
              <div class="offer-icon">🔥</div>
              <div class="offer-info">
                <div class="offer-title">3日免费体验</div>
                <div class="offer-desc">传人会员全部权限</div>
              </div>
            </div>
            <div class="offer-item">
              <div class="offer-icon">🎁</div>
              <div class="offer-info">
                <div class="offer-title">邀请返现</div>
                <div class="offer-desc">成功邀请得¥10</div>
              </div>
            </div>
            <div class="offer-item">
              <div class="offer-icon">💎</div>
              <div class="offer-info">
                <div class="offer-title">购买即送</div>
                <div class="offer-desc">数字艺术海报</div>
              </div>
            </div>
          </div>
          <button class="btn btn-primary promotion-button" @click="upgradeMembership">
            立即抢购
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 页面容器 */
.modern-adaptations-container {
  min-height: 100vh;
  background-color: var(--color-background);
}

/* 页面头部 */
.page-header {
  background-color: var(--color-secondary);
  color: white;
  padding: 3rem 0;
  text-align: center;
}

.page-title {
  font-size: 2.5rem;
  margin: 0 0 0.5rem 0;
  font-weight: bold;
}

.page-subtitle {
  font-size: 1.2rem;
  margin: 0;
  opacity: 0.9;
}

/* 会员提示横幅 */
.membership-banner {
  background-color: var(--color-background-soft);
  border-bottom: 1px solid var(--color-border);
}

.banner-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 0;
}

.banner-text h3 {
  margin: 0 0 0.5rem 0;
  color: var(--color-primary);
}

.banner-text p {
  margin: 0;
  color: var(--color-text);
}

.user-level {
  font-weight: bold;
  color: var(--color-secondary);
}

.banner-actions {
  display: flex;
  gap: 1rem;
}

/* 通用区块样式 */
.section {
  padding: 3rem 0;
}

.section-header {
  text-align: center;
  margin-bottom: 2rem;
}

.section-title {
  font-size: 2rem;
  margin: 0 0 0.5rem 0;
  color: var(--color-secondary);
}

.section-subtitle {
  font-size: 1.1rem;
  color: var(--color-text-light);
  margin: 0;
}

/* 内容网格 */
.content-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 2rem;
}

.content-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.content-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}

/* 内容封面 */
.content-cover {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.content-card:hover .cover-image {
  transform: scale(1.05);
}

.exclusive-badge {
  position: absolute;
  top: 1rem;
  left: 1rem;
  background-color: rgba(255, 193, 7, 0.9);
  color: white;
  padding: 0.3rem 0.8rem;
  border-radius: 4px;
  font-size: 0.9rem;
  font-weight: bold;
}

.limited-badge {
  position: absolute;
  top: 1rem;
  left: 1rem;
  background-color: rgba(220, 53, 69, 0.9);
  color: white;
  padding: 0.3rem 0.8rem;
  border-radius: 4px;
  font-size: 0.9rem;
  font-weight: bold;
}

.rating-badge {
  position: absolute;
  bottom: 1rem;
  right: 1rem;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 0.3rem 0.8rem;
  border-radius: 4px;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
  gap: 0.3rem;
}

.rating-stars {
  color: #ffd700;
}

.rating-score {
  font-weight: bold;
}

.rating-count {
  color: var(--color-text-light);
  font-size: 0.8rem;
}

/* 内容信息 */
.content-info {
  padding: 1.5rem;
}

.content-title {
  font-size: 1.5rem;
  margin: 0 0 0.5rem 0;
  color: var(--color-secondary);
}

.series-info {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
}

.series-tag {
  background-color: var(--color-primary-light);
  color: var(--color-primary);
  padding: 0.2rem 0.6rem;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: bold;
}

.episode-count {
  color: var(--color-text-light);
  font-size: 0.9rem;
}

.content-description {
  color: var(--color-text);
  line-height: 1.6;
  margin-bottom: 1rem;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 亮点 */
.highlights {
  margin-bottom: 1rem;
}

.highlight-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
  font-size: 0.9rem;
  color: var(--color-text-light);
}

/* 操作区 */
.content-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1rem;
}

.price-info {
  display: flex;
  align-items: baseline;
  gap: 0.5rem;
}

.discount-price {
  font-size: 1.5rem;
  font-weight: bold;
  color: var(--color-error);
}

.original-price {
  font-size: 1rem;
  color: var(--color-text-light);
  text-decoration: line-through;
}

/* 数字藏品 */
.collectibles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 2rem;
}

.collectible-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.collectible-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}

.collectible-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.item-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background-color: var(--color-background-soft);
}

.collectible-info {
  padding: 1.5rem;
}

.collectible-name {
  font-size: 1.3rem;
  margin: 0 0 0.5rem 0;
  color: var(--color-secondary);
}

.collectible-description {
  color: var(--color-text);
  line-height: 1.6;
  margin-bottom: 1rem;
  font-size: 0.95rem;
}

.quantity-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 1rem;
  font-size: 0.9rem;
  color: var(--color-text-light);
}

.quantity-remaining {
  font-weight: bold;
  color: var(--color-secondary);
}

.collectible-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.collectible-rating {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  font-size: 0.9rem;
}

.collectible-price {
  font-size: 1.3rem;
  font-weight: bold;
  color: var(--color-error);
}

.full-width {
  width: 100%;
}

button:disabled {
  background-color: var(--color-text-light);
  cursor: not-allowed;
}

/* 促销活动 */
.promotion-section {
  padding: 2rem 0 4rem 0;
}

.promotion-card {
  background-color: linear-gradient(135deg, var(--color-primary) 0%, var(--color-secondary) 100%);
  background-image: linear-gradient(135deg, var(--color-primary) 0%, var(--color-secondary) 100%);
  color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 2rem;
}

.promotion-header {
  text-align: center;
  margin-bottom: 2rem;
}

.promotion-title {
  font-size: 2rem;
  margin: 0 0 0.5rem 0;
}

.promotion-subtitle {
  font-size: 1.2rem;
  margin: 0;
  opacity: 0.9;
}

.promotion-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 2rem;
}

.promotion-offers {
  display: flex;
  gap: 2rem;
  flex-wrap: wrap;
}

.offer-item {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.offer-icon {
  font-size: 2rem;
}

.offer-info .offer-title {
  font-weight: bold;
  font-size: 1.1rem;
  margin-bottom: 0.2rem;
}

.offer-info .offer-desc {
  opacity: 0.9;
  font-size: 0.9rem;
}

.promotion-button {
  font-size: 1.1rem;
  padding: 0.8rem 2rem;
  min-width: 150px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .banner-content {
    flex-direction: column;
    text-align: center;
    gap: 1rem;
  }
  
  .content-grid,
  .collectibles-grid {
    grid-template-columns: 1fr;
  }
  
  .promotion-content {
    flex-direction: column;
    text-align: center;
  }
  
  .promotion-offers {
    justify-content: center;
  }
}
</style>